package com.auth.config.handler;

import com.auth.system.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.utility.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author
 */
public class AuthSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException{
        response.setContentType("application/json;charset=utf-8");
        Result result = Result.returnCodeSuccess();
        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(result);
        userService.updateOnline(((User) authentication.getPrincipal()).getUsername());
        response.getWriter().write(s);
    }
}
